import os
# import face_recognition
import hashlib

import sqlite3

import file_util as fu


valid_ext_arr = ['jpg', 'jpeg', 'png', 'psd', 'gif', 'pef', 'bmp']

conn = None
cursor = None


def get_eg_img():
    eg_img = face_recognition.load_image_file("D:\\Workspace\\my\\scripts\\python\\file_tidy\\eg\\aobama.jpg")
    eg_img_encoding = face_recognition.face_encodings(eg_img)[0]


def save_file_info(data):
    try:
        sql = 'insert into os_storage_files (size,dir,filename,ext,sign,num) values (?,?,?,?,?,?)'
        cursor.execute(sql, data)
        conn.commit()
    except Exception as e:
        print(e)


def save_dup_file_info(data):
    try:
        sql = 'insert into os_storage_duplicate_files (size,dir,filename,sign) values (?,?,?,?)'
        cursor.execute(sql, data)
        conn.commit()
        sql = 'update os_storage_files set num=num+1 where sign=?'
        cursor.execute(sql, [data[3]])
        conn.commit()
    except Exception:
        pass


def get_file(sign):
    row = {}
    try:
        sql = 'select id,dir,filename from os_storage_files where sign=? limit 1'
        cursor.execute(sql, [sign])
        data = cursor.fetchone()
        if data is not None:
            row = data
    except Exception as e:
        print(e)
        pass
    return row


def get_all_files(target_dir):
    files = []
    list_files = os.listdir(target_dir)
    for i in range(0, len(list_files)):
        path = os.path.join(target_dir, list_files[i])
        if os.path.isdir(path):
            files.extend(get_all_files(path))
        elif os.path.isfile(path):
            ext = fu.get_file_extension(path)
            if ext in valid_ext_arr:
                files.append({'path': path, 'ext': ext})
    return files


def loop_exec():
    dir_all_files = get_all_files('D:\\Workspace\\my\\scripts\\python\\file_tidy\\x')
    arr = []
    for file_obj in dir_all_files:
        file_path = file_obj.get('path')
        unknown_img = face_recognition.load_image_file(file_path)
        unknown_img_encoding = face_recognition.face_encodings(unknown_img)[0]
        results = face_recognition.compare_faces([eg_img_encoding], unknown_img_encoding)
        is_match = results[0]
        arr.append({'path': file_path, 'result': is_match})
    print(arr)


#获取文件的MD5值，适用于小文件
def get_file_md5(filepath):
    if os.path.isfile(filepath):
        f = open(filepath,'rb')
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        hash = md5obj.hexdigest()
        f.close()
        return str(hash).upper()
    return None

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

def start_tidy(file_dir):
    files = get_all_files(file_dir)
    for fo in files:
        fp = fo.get('path')
        size = os.path.getsize(fp)
        basedir, filename = os.path.split(fp)
        sign = get_file_md5(fp)
        db_file = get_file(sign)
        db_file_id = db_file.get('id', 0)
        if db_file_id > 0:
            db_dir = db_file.get('dir')
            db_filename = db_file.get('filename')
            if db_dir != basedir or filename != db_filename:
                data = (size, basedir, filename, sign)
                save_dup_file_info(data)
            else:
                print('文件重复')
        else:
            ext = fo.get('ext')
            data = (size, basedir, filename, ext, sign, 0)
            save_file_info(data)


conn = sqlite3.connect('app.db')
conn.row_factory = dict_factory
cursor = conn.cursor()
# start_tidy('D:\\Workspace\\my\\scripts\\python\\file_tidy\\x')
start_tidy('F:\\DCIM')
try:
    if conn is not None:
        conn.close()
except Exception as e:
    print(e)